package apptoko.com;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu;
import main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu.OnItemSelectedListener;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.graphics.Shader.TileMode;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.db.DatabaseHelper;
import apptoko.com.download.DownloadManager;
import apptoko.com.download.DownloadService;
import apptoko.com.download.DownloadManager.Request;
import apptoko.com.event.Event;
import apptoko.com.event.Event.BuyFailEvent;
import apptoko.com.event.Event.BuySuccessEvent;
import apptoko.com.event.Event.GetDownloadLinkFailEvent;
import apptoko.com.event.Event.GetDownloadLinkSuccess;
import apptoko.com.event.Event.GetTorrentDownloadLinkFail;
import apptoko.com.event.Event.GetTorrentDownloadLinkSuccess;
import apptoko.com.event.Event.HasGiftBox;
import apptoko.com.event.Event.NoticeHasExtrasDataEvent;
import apptoko.com.event.Event.OutOfGiftBox;
import apptoko.com.event.Event.UserInfoSuccessEvent;
import apptoko.com.event.Event.VersionBoughtEvent;
import apptoko.com.event.Event.VersionNotBoughtEvent;
import apptoko.com.fragment.CommentsFragment;
import apptoko.com.fragment.DetailsFragment;
import apptoko.com.fragment.RelatedAppsFragment;
import apptoko.com.model.ContentItemInfo;
import apptoko.com.model.DownloadLaterItem;
import apptoko.com.model.DownloadLink;
import apptoko.com.model.GiftSetting;
import apptoko.com.model.RelatedItems;
import apptoko.com.network.InstallBackgroundTask;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.CommonUtils;
import apptoko.com.util.Constants;
import apptoko.com.util.StorageUtils;
import apptoko.com.util.Utils;
import apptoko.com.view.AlertDialogManager;
import apptoko.com.view.CustomDialog;
import apptoko.com.view.FeedBackDialog;
import apptoko.com.view.MyWebView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.androidquery.AQuery;
import com.appota.asdk.commons.AccessTokenUtil;
import com.appota.asdk.topup.TopupAPI;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.easy.facebook.android.facebook.FBLoginManager;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.plus.PlusShare;

import de.greenrobot.event.EventBus;

@SuppressLint("InlinedApi")
public class DetailsActivity extends SherlockFragmentActivity implements OnTabChangeListener, OnClickListener {
	
	private AQuery aq;
	private TabHost  mTabHost;
	public static final String TAB_DETAILS = "details";
	public static final String TAB_COMMENT = "comments";
	public static final String TAB_RELATED_APPs = "relatedApp";
    private int mCurrentTab = 0;
    private ContentItemInfo item;
    private String contentType;
    private Typeface robotoBoldCond;
    private String store;
    private int from;
    private DatabaseHelper db;
    private DownloadManager downloadManager;
    private BackgroundTasks bgTask;
    private ProgressDialog pDialog;
    private Cursor cursor;
	private int mStatusColumnId;
	private int mIdColoumn;
	private long downloadId;
	private LinearLayout layoutProgress;
	private ProgressBar progressBar;
	private TextView textProgress;
	private ImageButton btnPauseResume;
	private ImageButton btnCancel;
	private String versionName = "";
	private boolean isQuickDownload = true;
	private int greenTym = -1;
	private int purpleTym = -1;
	private PackageEventReceiver receiver;
	private boolean isWatchMovie = false;
	private FBLoginManager fbLoginManager;
	private DownloadCanceledReceiver r;
	private String accessToken;
	private DialogInterface.OnClickListener onClick;
	private String previousScreen;
	private int versionId = 0;
	private String countryCode;
	private boolean enaG=false;
	private int autoInstall = 0;
	private boolean isDownloadData = false;
	private boolean isDownloadEpisode = false;
	private boolean hasGift = false;
	private String language;
	boolean come_back = false;
	private String username;
	private ProgressDialog downloadUpdateProgress;
	private String[] vers,links=null;
	private Twitter twitter;
	private RequestToken requestToken;
	private static SharedPreferences mSharedPreferences;
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		item = (ContentItemInfo) getIntent().getExtras().getSerializable(Constants.ITEM_INFO);
		contentType = item.getApplicationType();
//		if(contentType.equalsIgnoreCase("android")){
//			setTheme(R.style.Theme_Styled_Apps);
//			setThemeLowEndDevice(R.drawable.action_bar_apps);
//		} else if(contentType.equalsIgnoreCase("ebook")){
//			setTheme(R.style.Theme_Styled_Book);
//			setThemeLowEndDevice(R.drawable.action_bar_book);
//		} else if(contentType.equalsIgnoreCase("comic")){
//			setTheme(R.style.Theme_Styled_Comic);
//			setThemeLowEndDevice(R.drawable.action_bar_comic);
//		} else if(contentType.equalsIgnoreCase("film")){
//			setTheme(R.style.Theme_Styled_Movie);
//			setThemeLowEndDevice(R.drawable.action_bar_movie);
//		} else {
			setTheme(R.style.Theme_Styled_Home);
			setThemeLowEndDevice(R.drawable.action_bar_home);
//		}
		super.onCreate(arg0);
		
		initView();
//		if(checkLogin()){
//			getTorrentLink();
//		}
	}

	private void getTorrentLink() {
		bgTask.getTorrentDownloadLink(accessToken, item.getApplicationId());
		aq.id(R.id.btn_get_tr_download).clicked(null);
		aq.id(R.id.btn_get_tr_download).text("Getting Torrent..");
	}
	
	private void initView() {
		// TODO Auto-generated method stub
		Log.e("", "initView ");
		getSupportActionBar().setTitle(R.string.details);
		setContentView(R.layout.activity_details);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		
		EasyTracker.getInstance().setContext(this);
		store = getIntent().getStringExtra(Constants.STORE_KEY);
		from = getIntent().getIntExtra(Constants.FROM, 0);
		countryCode = Utils.getStaticCountryCode(getApplicationContext());
		SharedPreferences shared= getSharedPreferences("system_pre", MODE_PRIVATE);
		enaG=shared.getBoolean(Constants.ENABLE_GUEST, false);
		previousScreen = getIntent().getStringExtra(Constants.PREVIOUS_SCREEN);
		layoutProgress = (LinearLayout) findViewById(R.id.layout_progress);
		progressBar = (ProgressBar) layoutProgress.findViewById(R.id.details_progress);
		textProgress = (TextView) layoutProgress.findViewById(R.id.text_progress);
		btnPauseResume = (ImageButton) layoutProgress.findViewById(R.id.btn_pause_resume);
		btnCancel = (ImageButton) layoutProgress.findViewById(R.id.btn_cancel);
		((TextView)findViewById(R.id.details_name)).setSelected(true);
		downloadUpdateProgress=new ProgressDialog(this);
		downloadUpdateProgress.setIndeterminate(false);
		downloadUpdateProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		downloadUpdateProgress.setMax(100);
		downloadUpdateProgress.setMessage(getResources().getString(R.string.loading));
		bgTask = new BackgroundTasks(this);
//		checkRemainGift();
//		getUserInfo();
		db = new DatabaseHelper(this);
		aq = new AQuery(this);
		aq.overridePendingTransition5(R.anim.fade_in, R.anim.fade_in);
		downloadManager = new DownloadManager(getContentResolver(), getPackageName());
	    downloadManager.setAccessAllDownloads(false);
		startDownloadService();
		aq.id(R.id.details_author).clicked(this);
		receiver = new PackageEventReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_PACKAGE_ADDED);
		filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		filter.addDataScheme("package");
		registerReceiver(receiver, filter);
		
		r = new DownloadCanceledReceiver();
		IntentFilter f = new IntentFilter();
		f.addAction(Constants.ACTION_CANCEL_DOWNLOAD);
		registerReceiver(r, f);
		setupCursor();
		if(((AppStoreVnApplication)getApplication()).enableTor){
			aq.id(R.id.btn_get_tr_download).visibility(View.VISIBLE).enabled(true);
		}else{
			aq.id(R.id.btn_get_tr_download).visibility(View.GONE).enabled(false);
		}
		autoInstall = getIntent().getIntExtra(Constants.AUTO_INSTALL, 0);
		if(autoInstall == 1 || item.getHasPromotion() == 1){
			if(checkLogin()){
				pDialog = ProgressDialogManager.showProgressDialog(DetailsActivity.this, R.string.loading);
//				validAndBuy(0, "free", 0, 1);
//				if(isQuickDownload){
//					bgTask.getDownloadLink("", accessToken, event.getSlug(), 0, Utils.getStaticIsRooted(this), "direct");
//				} else {
//					bgTask.getDownloadLink("", accessToken, event.getSlug(), event.getVersionId(), Utils.getStaticIsRooted(this), "direct");
//				}
			}
		}
		language= UILApplication.getInstance().getConfig().locale.getLanguage();
		robotoBoldCond = Typeface.createFromAsset(getAssets(), getResources().getString(R.string.roboto_bold_condensed));
		float ratio = 0;
		if(contentType.equalsIgnoreCase("ebook") || contentType.equalsIgnoreCase("comic")){
			ratio = 1.0f / 1.0f;
		} else {
			ratio = AQuery.RATIO_PRESERVE;
		}
		if(item.getGiftbox() == 1){
			aq.id(R.id.ribbon_gift).visible();
		} else {
			aq.id(R.id.ribbon_gift).gone();
		}
		setButtonsColor(contentType);
		accessToken = Utils.getStaticAccessToken(this);
		aq.id(R.id.details_icon).image(item.getAvatar(), false, true, 0, 0, null, AQuery.FADE_IN, ratio);
		System.err.println(item.getAvatar());
		aq.id(R.id.details_name).text(item.getTitle()).typeface(robotoBoldCond);
		aq.id(R.id.details_author).text(item.getAuthor());
		aq.id(R.id.btn_download).clicked(this);
		aq.id(R.id.btn_download_later).clicked(this);
		if(db.checkAppInstalled(item.getPackageName())||Utils.isPackageExisted(this, item.getPackageName())){
			aq.id(R.id.btn_quick_download).gone();
			aq.id(R.id.btn_get_tr_download).gone();
			aq.id(R.id.btn_open).visible().enabled(true).clicked(this);
			aq.id(R.id.btn_uninstall).visible().clicked(this);
		} else {
			aq.id(R.id.btn_quick_download).visible().clicked(this);
			aq.id(R.id.btn_quick_download).visibility(View.VISIBLE);
			aq.id(R.id.btn_open).visibility(View.GONE).enabled(false);
			aq.id(R.id.btn_uninstall).gone();
		}
		if(checkLogin()){
			if(UILApplication.getInstance().username!=null &&( UILApplication.getInstance().username.equalsIgnoreCase("n2a5me")||UILApplication.getInstance().username.equalsIgnoreCase("quydo")||UILApplication.getInstance().username.equalsIgnoreCase("beobeo123beo")||UILApplication.getInstance().username.equalsIgnoreCase("muabu0n"))){
				aq.id(R.id.btn_checkDescription).visible().clicked(this);
			}else{
				aq.id(R.id.btn_checkDescription).visibility(View.GONE).clicked(null);
			}
			
		}else{
			aq.id(R.id.btn_checkDescription).visibility(View.GONE).clicked(null);
		}
		_vers=new ArrayList<String>();
		_verids=new ArrayList<String>();
		for (int i = 0;i<item.getVersionList().size();i++) {
			if(item.getVersions().get(i).getHave_torrent()==0){
				continue;
			}
			_vers.add("Version: "+item.getVersionList().get(i).getName());
			_verids.add(String.valueOf(item.getVersionList().get(i).getId()));
		}
		if(_vers.size()>0&&((AppStoreVnApplication)getApplication()).enableTor&&(!db.checkAppInstalled(item.getPackageName())&&!Utils.isPackageExisted(this, item.getPackageName()))){
			vers=_vers.toArray(new String[_vers.size()]);
			links=_verids.toArray(new String[_verids.size()]);
			aq.id(R.id.btn_get_tr_download).visibility(View.VISIBLE);
			aq.id(R.id.btn_get_tr_download).clicked(this).enabled(true);
			aq.id(R.id.btn_quick_download).visible().clicked(this);
		}else{
			aq.id(R.id.btn_get_tr_download).visibility(View.GONE);
			aq.id(R.id.btn_get_tr_download).clicked(null).enabled(false);
//			TextView childLayout = (TextView) findViewById(R.id.btn_quick_download);
//			LayoutParams layout=new LayoutParams(LayoutParams.WRAP_CONTENT, android.app.ActionBar.LayoutParams.WRAP_CONTENT);
////			layout.setMargins(10, 0, 10, 0);
////			layout.gravity = Gravity.CENTER;
//			childLayout.setLayoutParams(layout);
//			childLayout.setGravity(Gravity.CENTER);
		}
		
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		setupTabs(come_back);
		mTabHost.setOnTabChangedListener(this);
		Log.e("", "mCurrentTab "+mCurrentTab);
	    mTabHost.setCurrentTab(mCurrentTab);
	    updateTab(TAB_DETAILS, R.id.tab_details);
	    mSharedPreferences = getApplicationContext().getSharedPreferences(
                "MyPref", 0);
	}

	private void setThemeLowEndDevice(int drawableId){
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(drawableId);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
	}
	
	private void checkRemainGift(){
		if(item.getGiftbox() == 1){
			accessToken = Utils.getStaticAccessToken(this);
			bgTask.checkRemainGift(accessToken, item.getApplicationId());
		}
	}
	
	public void onEventMainThread(HasGiftBox e){
		hasGift = true;
	}
	
	public void onEventMainThread(OutOfGiftBox e){
		hasGift = false;
	}
	
	private void getUserInfo(){
		String accessToken = Utils.getStaticAccessToken(this);
		if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
			bgTask.getUserInfo(accessToken);
		}
	}
	
	public void onEventMainThread(UserInfoSuccessEvent event){
		greenTym = event.getUser().getGreenTym();
		purpleTym = event.getUser().getPurpleTym();
		username = event.getUser().getUserName();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString(Constants.USERNAME_LOGGEDIN, username).commit();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if(null == previousScreen || previousScreen.equals(null)){
			previousScreen = "";
		}
		EasyTracker.getTracker().sendView(previousScreen + "/Details/" + item.getTitle());
	}
	
	private void setButtonsColor(String contentType){
		if(contentType.equalsIgnoreCase("android")){
			aq.id(R.id.btn_quick_download).background(R.drawable.btn_green_selector);
			aq.id(R.id.btn_open).visible().background(R.drawable.btn_green_selector);
			aq.id(R.id.btn_uninstall).background(R.drawable.btn_green_selector);
		} else if(contentType.equalsIgnoreCase("ebook")){
			aq.id(R.id.btn_quick_download).background(R.drawable.btn_orange_selector);
			aq.id(R.id.btn_open).visible().background(R.drawable.btn_orange_selector);
			aq.id(R.id.btn_uninstall).background(R.drawable.btn_orange_selector);
		} else if(contentType.equalsIgnoreCase("comic")){
			aq.id(R.id.btn_quick_download).background(R.drawable.btn_blue_selector);
			aq.id(R.id.btn_open).visible().background(R.drawable.btn_blue_selector);
			aq.id(R.id.btn_uninstall).background(R.drawable.btn_blue_selector);
		} else if(contentType.equalsIgnoreCase("film")){
			aq.id(R.id.btn_quick_download).background(R.drawable.btn_red_selector).text(R.string.watch_trailer);
			aq.id(R.id.btn_open).visible().background(R.drawable.btn_red_selector);
			aq.id(R.id.btn_uninstall).background(R.drawable.btn_red_selector);
		}
	}
	
	private void setupCursor(){
		DownloadManager.Query baseQuery = new DownloadManager.Query().setOnlyIncludeVisibleInDownloadsUi(true).setFilterByTitle(item.getTitle());
		if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
			baseQuery.setFilterByMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
		} else if(store.equalsIgnoreCase("books")){
			baseQuery.setFilterByMimeType(StorageUtils.EBOOK_ROOT.toLowerCase(Locale.US));
		} else if(store.equalsIgnoreCase("comics")){
			baseQuery.setFilterByMimeType(StorageUtils.COMIC_ROOT.toLowerCase(Locale.US));
		} else if(store.equalsIgnoreCase("movies")){
			baseQuery.setFilterByMimeType(StorageUtils.MOVIES_ROOT.toLowerCase(Locale.US));
		} else {
			baseQuery.setFilterByMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
		}
		cursor = downloadManager.query(baseQuery);
		if(cursor == null || cursor.getCount() <= 0){
			return;
		}
		cursor.moveToFirst();
		mStatusColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
		mIdColoumn = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
	}
	
	private void updateProgress(int progress, String progressText){
		setupCursor();
		layoutProgress.setVisibility(View.VISIBLE);
		cursor.moveToFirst();
		int status =0;
		try{
			status= cursor.getInt(mStatusColumnId);
			downloadId = cursor.getInt(mIdColoumn);
		}catch(CursorIndexOutOfBoundsException ex){
			progressBar.setProgress(progress);
			textProgress.setText(progressText);
			return;
		}
		
		boolean indeterminate = status == DownloadManager.STATUS_PENDING;
		progressBar.setIndeterminate(indeterminate);
		if (!indeterminate) {
			progressBar.setProgress(progress);
			textProgress.setText(progressText);
		}
		if (status == DownloadManager.STATUS_FAILED) {
			layoutProgress.setVisibility(View.GONE);
			aq.id(R.id.btn_quick_download).visible().clicked(this);
			aq.id(R.id.btn_open).gone();
			aq.id(R.id.btn_uninstall).gone();
			cursor.close();
		} else if(status == DownloadManager.STATUS_SUCCESSFUL){
			layoutProgress.setVisibility(View.GONE);
			aq.id(R.id.btn_quick_download).invisible().enabled(false);
			aq.id(R.id.btn_open).gone();
			aq.id(R.id.btn_uninstall).gone();
			cursor.close();
		} else if(status == DownloadManager.STATUS_PAUSED){
			layoutProgress.setVisibility(View.VISIBLE);
			aq.id(R.id.btn_quick_download).gone();
			aq.id(R.id.btn_open).gone();
			aq.id(R.id.btn_uninstall).gone();
			btnPauseResume.setImageResource(R.drawable.ic_resume);
			btnPauseResume.setContentDescription(getString(R.string.resume_download));
			textProgress.setText(progressText);
			btnPauseResume.setOnClickListener(this);
			btnCancel.setOnClickListener(this);
		} else {
			if(layoutProgress.getVisibility() == View.GONE){
				layoutProgress.setVisibility(View.VISIBLE);
			}
			aq.id(R.id.btn_quick_download).gone();
			aq.id(R.id.btn_open).gone();
			aq.id(R.id.btn_uninstall).gone();
			btnPauseResume.setImageResource(R.drawable.ic_pause);
			btnPauseResume.setContentDescription(getString(R.string.pause));
			textProgress.setText(progressText);
			btnPauseResume.setOnClickListener(this);
			btnCancel.setOnClickListener(this);
		}
	}
	
	public void onEventMainThread(Event.UpdateDownloadProgressEvent event){
		if(event.getTitle().equalsIgnoreCase(item.getTitle())){
			int progress = getProgressValue(event.getTotalBytes(), event.getDownloadedBytes());
			updateProgress(progress, Utils.printSize(event.getDownloadedBytes()) + "/" + Utils.printSize(event.getTotalBytes()) + " ( " + progress + "% )");
		}
//		if(aq.id(R.id.btn_get_tr_download).visible().){
//			aq.id(R.id.btn_get_tr_download).visibility(View.INVISIBLE);
//			aq.id(R.id.btn_get_tr_download).clicked(null);
//		}
		
	}
	
	public void onEventMainThread(final Event.DownloadFailEvent e){
		if(e.getMessage() != null){
			if(e.getMessage().contains("exist")){
				AlertDialogManager am = new AlertDialogManager(this);
				am.showFileDowloadDialog(store, R.string.install_already_exist_file, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
							if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
								boolean autoInstall = getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).getBoolean(SettingsActivity.KEY_AUTO_INSTALL, false);
					    		if(!autoInstall){
					    			Utils.installAPK(DetailsActivity.this, StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
					    		} else {
					    			InstallBackgroundTask task = new InstallBackgroundTask(DetailsActivity.this);
					    			task.execute(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()), item.getTitle());
					    		}
							} else if(store.equalsIgnoreCase("books")){
								openEbook(StorageUtils.EBOOK_ROOT + Utils.getFileName(e.getPath()));
							} else if(store.equalsIgnoreCase("comics")){
								openComic(StorageUtils.COMIC_ROOT + Utils.getFileName(e.getPath()));
							} else {
								Intent watch = new Intent(DetailsActivity.this, VideoActivity.class);
								watch.putExtra(Constants.MOVIE_URL, StorageUtils.MOVIES_ROOT + Utils.getFileName(e.getPath()));
								watch.putExtra(Constants.MOVIE_TITLE, Utils.getFileName(e.getPath()));
								watch.putExtra(Constants.MOVIE_EPISODE, "");
								watch.putExtra(Constants.KEY_PRICE_1, 0);
								watch.putExtra(Constants.KEY_PRICE_2, 0);
								watch.putExtra(Constants.KEY_VERSION, 0);
								watch.putExtra(Constants.KEY_SLUG, "");
								watch.putExtra(Constants.IS_MOVIE_PURCHASED, true);
								startActivity(watch);
							}
							break;
						case DialogInterface.BUTTON_NEGATIVE:
							if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
								Utils.deleteFile(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
							} else if(store.equalsIgnoreCase("books")){
								Utils.deleteFile(StorageUtils.EBOOK_ROOT + Utils.getFileName(e.getPath()));
							} else if(store.equalsIgnoreCase("comics")){
								Utils.deleteFile(StorageUtils.COMIC_ROOT + Utils.getFileName(e.getPath()));
							} else {
								Utils.deleteFile(StorageUtils.MOVIES_ROOT + Utils.getFileName(e.getPath()));
							}
							break;
						case DialogInterface.BUTTON_NEUTRAL:
							dialog.dismiss();
							break;
						}
					}
				});
			} else {
				AppMsg.makeText(this, e.getMessage(), AppMsg.STYLE_CONFIRM, null).show();
			}
		}
		layoutProgress.setVisibility(View.GONE);
		if(_vers.size()>0&&((AppStoreVnApplication)getApplication()).enableTor){
			aq.id(R.id.btn_get_tr_download).visibility(View.VISIBLE);
			aq.id(R.id.btn_get_tr_download).clicked(this).enabled(true);
		}else{
			aq.id(R.id.btn_get_tr_download).visibility(View.GONE);
			aq.id(R.id.btn_get_tr_download).clicked(null).enabled(false);
		}
		aq.id(R.id.btn_open).visibility(View.GONE).enabled(false);
		aq.id(R.id.btn_uninstall).gone();
		downloadManager.remove(e.getId());
		cursor.close();
	}
	
	public void onEventMainThread(Event.DownloadSuccessEvent e){
		EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.DOWNLOAD_COMPLETE_ACTION, Constants.DOWNLOAD_COMPLETED + item.getTitle() + " in " + item.getApplicationType() + " store", Long.valueOf(1));
		layoutProgress.setVisibility(View.GONE);
		aq.id(R.id.btn_quick_download).invisible().enabled(false);
		aq.id(R.id.btn_open).gone();
		aq.id(R.id.btn_uninstall).gone();
		cursor.close();
	}
	
	private void setupTabs(boolean come_back2) {
        mTabHost.setup(); // you must call this before adding your tabs!
        if(!come_back2){
        	mTabHost.addTab(newTab(TAB_DETAILS, R.string.details, R.id.tab_details));
            mTabHost.addTab(newTab(TAB_COMMENT, R.string.comments, R.id.tab_comment));
            mTabHost.addTab(newTab(TAB_RELATED_APPs, R.string.relatedapp, R.id.tab_relateapp));
        }else{
        	Log.e("", "mTabHost.getTabWidget().getTabCount() "+mTabHost.getTabWidget().getTabCount());
        	if(mTabHost.getTabWidget().getTabCount()>0){
        		mTabHost.getTabWidget().removeAllViews();
			}
        	 mTabHost.addTab(newTab(TAB_DETAILS, R.string.details, R.id.tab_details));
             mTabHost.addTab(newTab(TAB_COMMENT, R.string.comments, R.id.tab_comment));
             mTabHost.addTab(newTab(TAB_RELATED_APPs, R.string.relatedapp, R.id.tab_relateapp));
             Log.e("", "mTabHost.getTabWidget().getTabCount() "+mTabHost.getTabWidget().getTabCount());
        }
           
        
    }
	
	private TabSpec newTab(String tag, int labelId, int tabContentId) {
		View indicator = null;
//		if(contentType.equalsIgnoreCase("android")){
//			indicator = LayoutInflater.from(this).inflate(R.layout.apps_tab, (ViewGroup) findViewById(android.R.id.tabs), false);
//		} else if(contentType.equalsIgnoreCase("ebook")){
//			indicator = LayoutInflater.from(this).inflate(R.layout.books_tab, (ViewGroup) findViewById(android.R.id.tabs), false);
//		} else if(contentType.equalsIgnoreCase("comic")){
//			indicator = LayoutInflater.from(this).inflate(R.layout.comics_tab, (ViewGroup) findViewById(android.R.id.tabs), false);
//		} else if(contentType.equalsIgnoreCase("film")){
//			indicator = LayoutInflater.from(this).inflate(R.layout.movies_tab, (ViewGroup) findViewById(android.R.id.tabs), false);
//		} else {
			indicator = LayoutInflater.from(this).inflate(R.layout.apps_tab, (ViewGroup) findViewById(android.R.id.tabs), false);
//		}
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.5f);
        indicator.setLayoutParams(params);
        TextView tabLabel = (TextView) indicator.findViewById(R.id.tab_text);
        tabLabel.setText(getResources().getString(labelId));
        tabLabel.setTypeface(robotoBoldCond);
        TabSpec tabSpec = mTabHost.newTabSpec(tag);
        tabSpec.setIndicator(indicator);
        tabSpec.setContent(tabContentId);
        return tabSpec;
    }
	
	private void updateTab(String tabId, int placeholder) {
        FragmentManager fm = getSupportFragmentManager();
        if(come_back){
        	if(tabId.equalsIgnoreCase(TAB_DETAILS)){
            		DetailsFragment dm = new DetailsFragment();
            		Bundle bundle = getIntent().getExtras();
            		bundle.putString(Constants.STORE_KEY, store);
            		bundle.putInt(Constants.FROM, from);
            		dm.setArguments(bundle);
                    fm.beginTransaction().replace(placeholder, dm, tabId).commit();
            } else if(tabId.equalsIgnoreCase(TAB_COMMENT)){
            		String appId = ((ContentItemInfo)getIntent().getExtras().getSerializable(Constants.ITEM_INFO)).getApplicationId();
            		CommentsFragment cm = new CommentsFragment();
            		Bundle bundle = new Bundle();
            		bundle.putString(Constants.SLUG, appId);
            		cm.setArguments(bundle);
                    fm.beginTransaction().replace(placeholder, cm, tabId).commit();
            }else{
            	RelatedAppsFragment rlaf = new RelatedAppsFragment();
        		Bundle bundle = new Bundle();
        		RelatedItems item=new RelatedItems();
        		bundle.putString(Constants.STORE_KEY, store);
        		bundle.putInt(Constants.FROM, from);
        		item.setRelatedApplications(this.item.getRelatedApplications());
        		bundle.putSerializable(Constants.ITEM_INFO, item);
        		rlaf.setArguments(bundle);
                fm.beginTransaction().replace(placeholder, rlaf, tabId).commit();
            }
        }else{
        	if(tabId.equalsIgnoreCase(TAB_DETAILS)){
            	if (fm.findFragmentByTag(tabId) == null) {
            		DetailsFragment dm = new DetailsFragment();
            		Bundle bundle = getIntent().getExtras();
            		bundle.putString(Constants.STORE_KEY, store);
            		bundle.putInt(Constants.FROM, from);
            		dm.setArguments(bundle);
                    fm.beginTransaction().replace(placeholder, dm, tabId).commit();
                }
            } else if(tabId.equalsIgnoreCase(TAB_COMMENT)) {
            	if (fm.findFragmentByTag(tabId) == null) {
            		String appId = ((ContentItemInfo)getIntent().getExtras().getSerializable(Constants.ITEM_INFO)).getApplicationId();
            		CommentsFragment cm = new CommentsFragment();
            		Bundle bundle = new Bundle();
            		bundle.putString(Constants.SLUG, appId);
            		cm.setArguments(bundle);
                    fm.beginTransaction().replace(placeholder, cm, tabId).commit();
                }
            }else{
            	RelatedAppsFragment rlaf = new RelatedAppsFragment();
        		Bundle bundle = new Bundle();
        		RelatedItems item=new RelatedItems();
        		item.setRelatedApplications(this.item.getRelatedApplications());
        		bundle.putString(Constants.STORE_KEY, store);
        		bundle.putInt(Constants.FROM, from);
        		bundle.putSerializable(Constants.ITEM_INFO, item);
        		rlaf.setArguments(bundle);
                fm.beginTransaction().replace(placeholder, rlaf, tabId).commit();
            }
        }
        
    }

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if(from == 10){
			Intent home = new Intent(DetailsActivity.this, HomeActivity.class);
			startActivity(home);
			finish();
		} else {
			super.onBackPressed();
		}
	}
	
	@Override
	protected void onPause() {
		Log.e("onPause","onPauseDetailsActivity");
		super.onPause();
		EventBus.getDefault().unregister(this);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.e("onResume","onResumeDetails");
		if(language.equals(UILApplication.getInstance().getConfig().locale.getLanguage())){
			super.onResume();
			invalidateOptionsMenu();
			EventBus.getDefault().register(this);
		}else{
			super.onResume();
			EventBus.getDefault().register(this);
			come_back = true;
			initView();
			invalidateOptionsMenu();
			come_back= false;
			language= UILApplication.getInstance().getConfig().locale.getLanguage();
		}
		com.facebook.AppEventsLogger.activateApp(this, getResources().getString(R.string.fb_app_id));
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(cursor != null){
			cursor.close();
		}
		unregisterReceiver(receiver);
		unregisterReceiver(r);
		Log.e("onDestroy","destroy details activity");
	}

	@Override
	public void onTabChanged(String tabId) {
		// TODO Auto-generated method stub
		if (TAB_DETAILS.equals(tabId)) {
            updateTab(tabId, R.id.tab_details);
            mCurrentTab = 0;
            return;
        }
        if (TAB_COMMENT.equals(tabId)) {
            updateTab(tabId, R.id.tab_comment);
            mCurrentTab = 1;
            return;
        }
        if (TAB_RELATED_APPs.equals(tabId)) {
            updateTab(tabId, R.id.tab_relateapp);
            mCurrentTab = 2;
            return;
        }
	}
	
	private int getProgressValue(long totalBytes, long currentBytes) {
		if (totalBytes == -1) {
			Log.e("totalByesDownload","0");
			return 0;
		}
		Log.e("totalByesDownload",totalBytes+"");
		return (int) (currentBytes * 100 / totalBytes);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getSupportMenuInflater().inflate(R.menu.activity_details, menu);
		SubMenu subMenu1 = menu.addSubMenu("SHARE");
		subMenu1.add(0, R.id.menu_share_barcode, 0, R.string.twitter).setIcon(R.drawable.twitter);
        subMenu1.add(0, R.id.menu_share_facebook, 1, R.string.facebook).setIcon(R.drawable.ic_facebook);
//        subMenu1.add(0, R.id.menu_share_sms, 2, R.string.sms).setIcon(R.drawable.ic_launcher_smsmms);
        subMenu1.add(0, R.id.menu_share_gplus, 2, R.string.gplus).setIcon(R.drawable.ic_share_gplus);
        subMenu1.add(0, R.id.menu_share_link, 3, R.string.share_link).setIcon(R.drawable.ic_action_share);
        MenuItem subMenu1Item = subMenu1.getItem();
        subMenu1Item.setIcon(R.drawable.ic_action_share);
        subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.menu_feedback:
			if(this.item.getTitle() != null){
				String content = this.item.getTitle()+"( link http://apptoko.com/a/details?id="+ this.item.getPackageName()+" )";
				FeedBackDialog customDialog = new FeedBackDialog(this,1,content,username==null?getResources().getString(R.string.visitorfeedback):username);
				customDialog.setTitle(R.string.feed_back);
				customDialog.show();
			}
			return true;
		case android.R.id.home:
			if(from == 2){
				finish();
			} else {
				Intent home = new Intent(DetailsActivity.this, HomeActivity.class);
				home.putExtra(Constants.STORE_KEY, store);
				home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(home);
				finish();
			}
			return true;
		case R.id.menu_search:
			Intent search = new Intent(this, SearchActivity.class);
			search.putExtra(Constants.SEARCH_TYPE, store);
			startActivity(search);
			return true;
		case R.id.menu_share_facebook:
			Intent i = new Intent(this, PostFacebookActivity.class);
			i.putExtra(Constants.SHARE_PICTURE, this.item.getAvatar());
			if(store.equalsIgnoreCase("books")){
				i.putExtra(Constants.SHARE_NAME, getResources().getString(R.string.ebook_type) + " " + this.item.getTitle());
			} else if(store.equalsIgnoreCase("comics")){
				i.putExtra(Constants.SHARE_NAME, getResources().getString(R.string.comic_type) + " " + this.item.getTitle());
			} else if(store.equalsIgnoreCase("movies")){
				i.putExtra(Constants.SHARE_NAME, getResources().getString(R.string.movie_type) + " " + this.item.getTitle());
			} else {
				i.putExtra(Constants.SHARE_NAME, getResources().getString(R.string.app_type) + " " + this.item.getTitle());
			}
			i.putExtra(Constants.SHARE_LINK, Constants.APPTOKO_PC + this.item.getPackageName());
			startActivity(i);
			break;
			case R.id.menu_share_sms:
				EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "share-sms", Long.valueOf(10));
				String smsBody = "";
				if(store.equals("home") || store.equals("apps")|| store.equals("games")){
					smsBody = getResources().getString(R.string.sms_app_invitation) + " " + Constants.APPTOKO_PC + this.item.getPackageName();
				} else if(store.equals("books")){
					smsBody = getResources().getString(R.string.sms_ebook_invitation) + " " + Constants.EBOOK_PC + this.item.getAppstorevnId();
				} else if(store.equals("comics")){
					smsBody = getResources().getString(R.string.sms_comic_invitation) + " " + Constants.COMIC_PC + this.item.getAppstorevnId();
				} else {
					smsBody = "";
				}
				Intent sms = new Intent(Intent.ACTION_VIEW);
				sms.putExtra("sms_body", smsBody);
				sms.setType("vnd.android-dir/mms-sms");
				startActivity(sms);
				return true;
			case R.id.menu_share_link:
				ClipboardManager clipboard=(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
				clipboard.setText(Constants.APPTOKO_PC + this.item.getPackageName());
				Toast.makeText(this,"Copied the link", Toast.LENGTH_LONG).show();
				break;
			case R.id.menu_share_gplus:
				String link = "http://apptoko.com/a/details?id="+this.item.getPackageName();
				// Launch the Google+ share dialog with attribution to your app.
			      Intent shareIntent = new PlusShare.Builder(this)
			          .setType("text/plain")
			          .setText(this.item.getTitle())
			          .setContentUrl(Uri.parse(link))
			          .getIntent();
			      startActivity(shareIntent);
				break;
			case R.id.menu_share_barcode:
//				e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
//	            e.putString(PREF_KEY_OAUTH_SECRET,
				if(pDialog!=null){
					pDialog.show();
				}
				twitterMsg=this.item.getTitle()+" : " +Constants.APPTOKO_PC + this.item.getPackageName();
				String tot=mSharedPreferences.getString(LoginActivity.PREF_KEY_OAUTH_TOKEN, "");
				String tots=mSharedPreferences.getString(LoginActivity.PREF_KEY_OAUTH_SECRET, "");
				long userid=mSharedPreferences.getLong(LoginActivity.PREF_USER_ID, 0);
				if(TextUtils.isEmpty(tot)){
					//go for login twiter;
					new GetRequestTokenAsyn().execute();
				}else{
					//share twitter
					new ShareTwitterAsync(tot, tots, userid).execute();
				}
//				EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "share-barcode", Long.valueOf(10));
//				String text = "";
//				if(store.equals("home") || store.equals("apps") || store.equals("games")){
//					text = Constants.APPSTOREVN_PC + this.item.getPackageName();
//				} else if(store.equals("books")){
//					text = Constants.EBOOK_PC + this.item.getAppstorevnId();
//				} else if(store.equals("comics")){
//					text = Constants.COMIC_PC + this.item.getAppstorevnId();
//				} else {
//					text = "";
//				}
//				Intent intent = new Intent(Intents.Encode.ACTION);
//			    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
//			    intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT);
//			    intent.putExtra(Intents.Encode.DATA, text);
//			    intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString());
//			    startActivity(intent);
				return true;
		case R.id.menu_account:
			boolean isLogin = Utils.getStaticIsLogin(this);
			if(isLogin){
				Intent account = new Intent(this, AccountActivity.class);
				startActivity(account);
			} else {
				Intent intent = new Intent(this, LoginActivity.class);
				intent.putExtra("goback",true);
				startActivityForResult(intent,222);
			}
			return true;
		case R.id.menu_manage:
			Intent manage;
			if(this.store.equalsIgnoreCase("apps") || this.store.equalsIgnoreCase("games") || this.store.equalsIgnoreCase("home")){
				manage = new Intent(this, AppManageActivity.class);
				manage.putExtra(Constants.STORE_KEY, this.store);
				startActivity(manage);
			} else if(this.store.equalsIgnoreCase("books") || this.store.equalsIgnoreCase("comics")){
				manage = new Intent(this, BookManageActivity.class);
				manage.putExtra(Constants.STORE_KEY, this.store);
				startActivity(manage);
			} else {
				manage = new Intent(this, MoviesManageActivity.class);
				manage.putExtra(Constants.STORE_KEY, this.store);
				startActivity(manage);
			}
			return true;
		case R.id.menu_setting:
			Intent setting = new Intent(this, SettingsActivity.class);
			startActivity(setting);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	private String twitterMsg=null;
	private class ShareTwitterAsync extends AsyncTask<Void, Void, Void>{
		private String ttk,ttks;
		private long userid;
		private boolean success=false;
		private String error_msg;
		public ShareTwitterAsync(String ttk,String ttks,long userid){
			this.ttk=ttk;
			this.ttks=ttks;
			this.userid=userid;
		}
		@Override
		protected void onPreExecute() {
			if(pDialog!=null && !pDialog.isShowing()){
				pDialog.show();
			}
		}
		@Override
		protected Void doInBackground(Void... params) {
			try {
                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
                builder.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
                AccessToken accessToken = new AccessToken(ttk, ttks,userid);
                Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

                // Update status
                twitter4j.Status response = twitter.updateStatus(twitterMsg);
                success=true;
                Log.d("Status", "> " + response.getText());
            } catch (TwitterException e) {
                // Error in updating status
                Log.d("Twitter Update Error", e.getMessage());
                error_msg=e.getMessage();
                e.printStackTrace();
            }
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			if(pDialog!=null && pDialog.isShowing()){
				pDialog.dismiss();
			}
			if(success){
				AppMsg.makeText(DetailsActivity.this, "Share on Twitter successfully!", AppMsg.STYLE_INFO, null).show();
			}else{
				AppMsg.makeText(DetailsActivity.this, error_msg, AppMsg.STYLE_ALERT, null).show();
			}
		}
	}
	public class GetRequestTokenAsyn extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(Constants.TWITTER_CONSUMER_KEY,Constants.TWITTER_CONSUMER_SECRET );
            try
            {
                requestToken = twitter.getOAuthRequestToken(LoginActivity.TWITTER_CALLBACK_URL);
            }
            catch (TwitterException e)
            {
                e.printStackTrace();
            }
			Intent loginIntent = new Intent(DetailsActivity.this, MyWebView.class);
            loginIntent.putExtra("url", requestToken.getAuthenticationURL());
            startActivityForResult(loginIntent, 222);
			return null;
		}
		
	}
	private void startDownloadService() {
		Intent intent = new Intent();
		intent.setClass(this, DownloadService.class);
		startService(intent);
	}
	
	private void download(View v, final main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem, final long vId, final boolean isQuickDownload, final boolean isWatchMovie, final int isBought){
		this.isQuickDownload = isQuickDownload;
		///
		if(menuItem == null){
			if(item.getApplicationType().equalsIgnoreCase("android")){
				validAndBuy(0, "free", vId, isBought);
//				AlertDialogManager am = new AlertDialogManager(this);
//				am.showWebViewDialog(aq, item.getInstallAttachApplication(), this, item.getPermission(), R.string.app_permissions, item.getAttachApplicationAvatar(), item.getAttachApplicationTitle(), new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						DetailsActivity.this.isQuickDownload = isQuickDownload;
//						if(item.getPrice() != 0){
//							validAndBuy(item.getPrice(), "green", vId, isBought);
//						} else if(item.getPrice2() != 0){
//							validAndBuy(item.getPrice2(), "purple", vId, isBought);
//						} else {
//							pDialog = ProgressDialogManager.showProgressDialog(DetailsActivity.this, R.string.loading);
//							validAndBuy(0, "free", vId, isBought);
//						}
//						dialog.dismiss();
//					}
//				});
			} else if(item.getApplicationType().equalsIgnoreCase("ebook") || item.getApplicationType().equalsIgnoreCase("comic")){
				this.isQuickDownload = isQuickDownload;
				if(item.getPrice() != 0){
					validAndBuy(item.getPrice(), "green", vId, isBought);
				} else if(item.getPrice2() != 0){
					validAndBuy(item.getPrice2(), "purple", vId, isBought);
				} else {
					pDialog = ProgressDialogManager.showProgressDialog(DetailsActivity.this, R.string.loading);
					validAndBuy(0, "free", vId, isBought);
				}
			} else if(item.getApplicationType().equalsIgnoreCase("film")){
				this.isWatchMovie = isWatchMovie;
				this.isQuickDownload = isQuickDownload;
				if(item.getVersionList().size() == 1){
					accessToken = Utils.getStaticAccessToken(this);
					pDialog = ProgressDialogManager.showProgressDialog(DetailsActivity.this, R.string.loading);
					versionId = item.getVersionList().get(0).getId();
					bgTask.watchMovie("", accessToken, item.getApplicationId(), versionId, Utils.getStaticIsRooted(this), "direct");
				} else {
					PopupMenu popupMenu = new PopupMenu(this);
					popupMenu.setHeaderTitle(getResources().getString(R.string.choose_episode));
					String versionName;
					int versionId;
					String appId;
					int price1;
					int price2;
					for (int i = 0;i< item.getVersionList().size();i++) {
						versionId = item.getVersionList().get(i).getId();
						versionName = item.getVersionList().get(i).getName();
						appId = item.getApplicationId();
						price1 = item.getVersionList().get(i).getPrice1();
						price2 = item.getVersionList().get(i).getPrice2();
						popupMenu.add(versionId, versionName, appId, price1, price2, true).setIcon(getResources().getDrawable(R.drawable.ic_arrow_down));
					}  
					popupMenu.setOnItemSelectedListener(new OnItemSelectedListener() {
						@Override
						public void onItemSelected(final main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
							// TODO Auto-generated method stub
							accessToken = Utils.getStaticAccessToken(DetailsActivity.this);
							DetailsActivity.this.versionName = menuItem.getTitle();
							DetailsActivity.this.isWatchMovie = isWatchMovie;
							DetailsActivity.this.isQuickDownload = isQuickDownload;
							pDialog = ProgressDialogManager.showProgressDialog(DetailsActivity.this, R.string.loading);
							DetailsActivity.this.versionId = menuItem.getItemId();
							bgTask.watchMovie("", accessToken, item.getApplicationId(), DetailsActivity.this.versionId, Utils.getStaticIsRooted(DetailsActivity.this), "direct");
						}
					});
					popupMenu.show(v);
				}
			}
		} else {
			if(item.getApplicationType().equalsIgnoreCase("android")){
				validAndBuy(0, "free", menuItem.getItemId(), isBought);
//				AlertDialogManager am = new AlertDialogManager(this);
//				am.showWebViewDialog(aq, item.getInstallAttachApplication(), this, item.getPermission(), R.string.app_permissions, item.getAttachApplicationAvatar(), item.getAttachApplicationTitle(), new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						DetailsActivity.this.isQuickDownload = isQuickDownload;
//						if(item.getPrice() != 0){
//							validAndBuy(menuItem.getPrice1(), "green", menuItem.getItemId(), isBought);
//						} else if(item.getPrice2() != 0){
//							validAndBuy(menuItem.getPrice2(), "purple", menuItem.getItemId(), isBought);
//						} else {
//							pDialog = ProgressDialogManager.showProgressDialog(DetailsActivity.this, R.string.loading);
//							validAndBuy(0, "free", menuItem.getItemId(), isBought);
//						}
//						dialog.dismiss();
//					}
//				});
			} else if(item.getApplicationType().equalsIgnoreCase("ebook") || item.getApplicationType().equalsIgnoreCase("comic")){
				this.isQuickDownload = isQuickDownload;
				if(item.getPrice() != 0){
					validAndBuy(menuItem.getPrice1(), "green", menuItem.getItemId(), isBought);
				} else if(item.getPrice2() != 0){
					validAndBuy(menuItem.getPrice2(), "purple", menuItem.getItemId(), isBought);
				} else {
					pDialog = ProgressDialogManager.showProgressDialog(DetailsActivity.this, R.string.loading);
					validAndBuy(0, "free", menuItem.getItemId(), isBought);
				}
			} else if(item.getApplicationType().equalsIgnoreCase("film")){
				this.isWatchMovie = isWatchMovie;
				this.isQuickDownload = isQuickDownload;
				if(item.getVersionList().size() == 1){
					accessToken = Utils.getStaticAccessToken(this);
					pDialog = ProgressDialogManager.showProgressDialog(DetailsActivity.this, R.string.loading);
					versionId = item.getVersionList().get(0).getId();
					bgTask.watchMovie("", accessToken, item.getApplicationId(), versionId, Utils.getStaticIsRooted(this), "direct");
				} else {
					PopupMenu popupMenu = new PopupMenu(this);
					popupMenu.setHeaderTitle(getResources().getString(R.string.choose_episode));
					String versionName;
					int versionId;
					String appId;
					int price1;
					int price2;
					for (int i =0;i< item.getVersionList().size();i++) {
						versionId = item.getVersionList().get(i).getId();
						versionName = item.getVersionList().get(i).getName();
						appId = item.getApplicationId();
						price1 = item.getVersionList().get(i).getPrice1();
						price2 = item.getVersionList().get(i).getPrice2();
						popupMenu.add(versionId, versionName, appId, price1, price2, true).setIcon(getResources().getDrawable(R.drawable.ic_arrow_down));
					}  
					popupMenu.setOnItemSelectedListener(new OnItemSelectedListener() {
						@Override
						public void onItemSelected(final main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
							// TODO Auto-generated method stub
							accessToken = Utils.getStaticAccessToken(DetailsActivity.this);
							DetailsActivity.this.versionName = menuItem.getTitle();
							DetailsActivity.this.isWatchMovie = isWatchMovie;
							DetailsActivity.this.isQuickDownload = isQuickDownload;
							pDialog = ProgressDialogManager.showProgressDialog(DetailsActivity.this, R.string.loading);
							DetailsActivity.this.versionId = menuItem.getItemId();
							bgTask.watchMovie("", accessToken, item.getApplicationId(), DetailsActivity.this.versionId, Utils.getStaticIsRooted(DetailsActivity.this), "direct");
						}
					});
					popupMenu.show(v);
				}
			}
		}

	}
	private List<String> _vers,_verids;
	@Override
	public void onClick(final View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_quick_download:
			isQuickDownload=true;
			isDownloadData = false;
			isDownloadEpisode = false;
			EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.QUICK_DOWNLOAD_ACTION, item.getTitle() + " in " + item.getApplicationType() + " store", Long.valueOf(1));
			if(enaG){
				//allow e
				if(true){//checkLogin()
					if(item.getGiftbox() == 1){
						if(hasGift){
							AlertDialogManager am = new AlertDialogManager(this);
							final DatabaseHelper db = new DatabaseHelper(this);
							GiftSetting gift = db.getGiftSync(item.getApplicationId());
							if(gift != null && gift.getReceived() == 1){
								download(v, null, 0, true, true, 1);
							} else {
								if(item.getGiftboxDaysToGet() == 0){
									final GiftSetting gs = new GiftSetting();
									gs.setReceived(0);
									gs.setDays(0);
									gs.setName(item.getPackageName());
									gs.setSlug(item.getApplicationId());
									gs.setAppName(item.getTitle());
									gs.setPicture(item.getAvatar());
									onClick = new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											db.addGift(gs);
											download(v, null, 0, true, true, 1);
										}
									};
									am.showGiftDialog(R.string.gift_message, 0, onClick);
								} else {
									final GiftSetting gs = new GiftSetting();
									gs.setReceived(0);
									gs.setDays(item.getGiftboxDaysToGet());
									gs.setName(item.getPackageName());
									gs.setSlug(item.getApplicationId());
									gs.setAppName(item.getTitle());
									gs.setPicture(item.getAvatar());
									gs.setTimeToReceive(Utils.calculateDaysToGetGift(item.getGiftboxDaysToGet()));
									onClick = new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											db.addGift(gs);
											download(v, null, 0, true, true, 1);
										}
									};
									am.showGiftDialog(R.string.gift_message_days, item.getGiftboxDaysToGet(), onClick);
								}
							}
						} else {
							download(v, null, 0, true, true, 1);
						}
					} else {
						download(v, null, 0, true, true, 1);
					}
				} else {
					AlertDialogManager am = new AlertDialogManager(this);
					am.showButtonsDialog(R.string.must_login_to_download, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
								Intent intent = new Intent(DetailsActivity.this, LoginActivity.class);
								intent.putExtra("goback",true);
								startActivityForResult(intent,222);
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				}
			}else{
				if(!countryCode.equalsIgnoreCase("id")&&!countryCode.equalsIgnoreCase("vn")&&!countryCode.equalsIgnoreCase("my")){
					if(item.getRootLink()!=null&&!item.getRootLink().equals(""))
					{
						Intent gp = new Intent(Intent.ACTION_VIEW);
						gp.setData(Uri.parse(item.getRootLink()));
						startActivity(gp);
					}else{
						AppMsg.makeText(this, "This item has no google play link currently", AppMsg.STYLE_ALERT, null).show();
					}
					
				} else {
					if(true){//checkLogin()
						if(item.getGiftbox() == 1){
							if(hasGift){
								AlertDialogManager am = new AlertDialogManager(this);
								final DatabaseHelper db = new DatabaseHelper(this);
								GiftSetting gift = db.getGiftSync(item.getApplicationId());
								if(gift != null && gift.getReceived() == 1){
									download(v, null, 0, true, true, 1);
								} else {
									if(item.getGiftboxDaysToGet() == 0){
										final GiftSetting gs = new GiftSetting();
										gs.setReceived(0);
										gs.setDays(0);
										gs.setName(item.getPackageName());
										gs.setSlug(item.getApplicationId());
										gs.setAppName(item.getTitle());
										gs.setPicture(item.getAvatar());
										onClick = new DialogInterface.OnClickListener() {
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												db.addGift(gs);
												download(v, null, 0, true, true, 1);
											}
										};
										am.showGiftDialog(R.string.gift_message, 0, onClick);
									} else {
										final GiftSetting gs = new GiftSetting();
										gs.setReceived(0);
										gs.setDays(item.getGiftboxDaysToGet());
										gs.setName(item.getPackageName());
										gs.setSlug(item.getApplicationId());
										gs.setAppName(item.getTitle());
										gs.setPicture(item.getAvatar());
										gs.setTimeToReceive(Utils.calculateDaysToGetGift(item.getGiftboxDaysToGet()));
										onClick = new DialogInterface.OnClickListener() {
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												db.addGift(gs);
												download(v, null, 0, true, true, 1);
											}
										};
										am.showGiftDialog(R.string.gift_message_days, item.getGiftboxDaysToGet(), onClick);
									}
								}
							} else {
								download(v, null, 0, true, true, 1);
							}
						} else {
							download(v, null, 0, true, true, 1);
						}
					} else {
						AlertDialogManager am = new AlertDialogManager(this);
						am.showButtonsDialog(R.string.must_login_to_download, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								switch (which) {
								case DialogInterface.BUTTON_POSITIVE:
									Intent intent = new Intent(DetailsActivity.this, LoginActivity.class);
									intent.putExtra("goback",true);
									startActivityForResult(intent,222);
									break;
								case DialogInterface.BUTTON_NEGATIVE:
									dialog.dismiss();
									break;
								}
							}
						});
					}
				}
			}
			
			break;
		case R.id.btn_get_tr_download:
			if(enaG){
				//allow e
				if(!isCallable()){
					showDownloadTorrentClient();
					}else{
					showTorrentLinks(vers);
					}
			}else{
				if(!countryCode.equalsIgnoreCase("id")&&!countryCode.equalsIgnoreCase("vn")&&!countryCode.equalsIgnoreCase("my")){
					if(item.getRootLink()!=null&&!item.getRootLink().equals(""))
					{
						Intent gp = new Intent(Intent.ACTION_VIEW);
						gp.setData(Uri.parse(item.getRootLink()));
						startActivity(gp);
					}else{
						AppMsg.makeText(this, "This item has no google play link currently", AppMsg.STYLE_ALERT, null).show();
					}
					
				} else 
				if(false){//!checkLogin()
					AlertDialogManager am = new AlertDialogManager(this);
					am.showButtonsDialog(R.string.must_login_to_download, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
								Intent intent = new Intent(DetailsActivity.this, LoginActivity.class);
								intent.putExtra("returnDetail",true);
								intent.putExtra("goback",true);
								startActivityForResult(intent,222);
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
					return;
				}else{
					if(!isCallable()){
					showDownloadTorrentClient();
					}else{
					showTorrentLinks(vers);
					}
				}
			}
//			if(links==null){
//				getTorrentLink();
//				return;
//			}
//			isQuickDownload=false;
//			isDownloadData = false;
//			isDownloadEpisode = false;
//			EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, "Get torrent links", item.getTitle() + " in " + item.getApplicationType() + " store", Long.valueOf(1));
//			if(!isCallable()){
//				//download torrent client
//				showDownloadTorrentClient();
//			}else{
//				if(vers.length>0){
//					showTorrentLinks(vers);
//				}
//			}
			break;
		case R.id.details_author:
			Log.e("click search","search author");
			Intent intent = new Intent(this, SearchResultActivity.class);
			intent.putExtra("developer", aq.id(R.id.details_author).getTextView().getText().toString());
			intent.putExtra(Constants.STORE_KEY, "");
			startActivity(intent);
			break;
		case R.id.btn_open:
			Utils.launch(this, item.getPackageName());
			break;
		case R.id.btn_uninstall:
			Utils.uninstallAPK(this, item.getPackageName());
			break;
		case R.id.btn_pause_resume:
			ImageButton button = (ImageButton) v;
			if(button.getContentDescription().toString().equalsIgnoreCase(getString(R.string.pause))){
				Cursor cursor = downloadManager.query(new apptoko.com.download.DownloadManager.Query().setFilterById(downloadId));
				try {
				    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
					    .moveToNext()) {
					int status = cursor
						.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
					if (status != DownloadManager.STATUS_RUNNING && status != DownloadManager.STATUS_PENDING) {
						
					}else
					{
						downloadManager.pauseDownload(downloadId);
						button.setImageResource(R.drawable.ic_resume);
						button.setContentDescription(getString(R.string.resume_download));
					}
				    }
				} finally {
				    cursor.close();
				}
				
			} else if(button.getContentDescription().toString().equalsIgnoreCase(getString(R.string.resume_download))){
				downloadManager.resumeDownload(downloadId);
				button.setImageResource(R.drawable.ic_pause);
				button.setContentDescription(getString(R.string.pause));
			}
			break;
		case R.id.btn_cancel:
			downloadManager.remove(downloadId);
			layoutProgress.setVisibility(View.GONE);
			//
			if(_vers.size()>0&&((AppStoreVnApplication)getApplication()).enableTor){
				vers=_vers.toArray(new String[_vers.size()]);
				links=_verids.toArray(new String[_verids.size()]);
				aq.id(R.id.btn_get_tr_download).visibility(View.VISIBLE);
				aq.id(R.id.btn_get_tr_download).clicked(this).enabled(true);
			}else{
				aq.id(R.id.btn_get_tr_download).visibility(View.GONE);
				aq.id(R.id.btn_get_tr_download).clicked(null).enabled(false);
			}
			//1
			aq.id(R.id.btn_quick_download).visible().clicked(this);
			aq.id(R.id.btn_open).visibility(View.GONE);
			aq.id(R.id.btn_open).enabled(false);
			aq.id(R.id.btn_uninstall).gone();
			break;
		case R.id.btn_download:
			isQuickDownload=false;
			EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.START_DOWNLOAD_ACTION, item.getTitle() + " in " + item.getApplicationType() + " store", Long.valueOf(1));
			if(enaG){
				//allow e
				if(true){//checkLogin()
					PopupMenu popupMenu = new PopupMenu(this);
					popupMenu.setHeaderTitle(getResources().getString(R.string.choose_version));
					String versionName;
					int versionId;
					String appId;
					int price1;
					int price2;
					for (int i = 0;i<item.getVersionList().size();i++) {
						versionId = item.getVersionList().get(i).getId();
						versionName = item.getVersionList().get(i).getName();
						appId = item.getApplicationId();
						price1 = item.getVersionList().get(i).getPrice1();
						price2 = item.getVersionList().get(i).getPrice2();
						popupMenu.add(versionId, versionName, appId, price1, price2, true).setIcon(getResources().getDrawable(R.drawable.ic_arrow_down));
					}  
					popupMenu.setOnItemSelectedListener(new OnItemSelectedListener() {
						@Override
						public void onItemSelected(final main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
							// TODO Auto-generated method stub
							if(menuItem.getPrice1() == 0 && menuItem.getPrice2() == 0){
								if(menuItem.getTitle().contains("Data") || menuItem.getTitle().contains("data")){
									isDownloadData = true;
								} else {
									isDownloadData = false;
								}
								if(menuItem.getTitle().contains("T-")){
									isDownloadEpisode = true;
								} else {
									isDownloadEpisode = false;
								}
								DetailsActivity.this.versionName = menuItem.getTitle();
								EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.DOWNLOAD_EVENT_CATEGORY, item.getTitle() + " of " + DetailsActivity.this.item.getTitle() + DetailsActivity.this.item.getApplicationType() + " store", Long.valueOf(1));
								if(item.getGiftbox() == 1){
									AlertDialogManager am = new AlertDialogManager(DetailsActivity.this);
									final DatabaseHelper db = new DatabaseHelper(DetailsActivity.this);
									GiftSetting gift = db.getGiftSync(item.getApplicationId());
									if(gift != null && gift.getReceived() == 1){
//										am.showPositiveDialog(R.string.gift_already_received, android.R.string.ok, new DialogInterface.OnClickListener() {
//											@Override
//											public void onClick(DialogInterface dialog, int which) {
//												dialog.dismiss();
//											}
//										});
										download(v, menuItem, 0, false, false, 1);
									} else {
										if(item.getGiftboxDaysToGet() == 0){
											final GiftSetting gs = new GiftSetting();
											gs.setReceived(0);
											gs.setDays(0);
											gs.setName(item.getPackageName());
											gs.setSlug(item.getApplicationId());
											gs.setAppName(item.getTitle());
											gs.setPicture(item.getAvatar());
											onClick = new DialogInterface.OnClickListener() {
												@Override
												public void onClick(DialogInterface dialog, int which) {
													// TODO Auto-generated method stub
													db.addGift(gs);
													download(v, menuItem, 0, false, false, 1);
												}
											};
											am.showGiftDialog(R.string.gift_message, 0, onClick);
										} else {
											final GiftSetting gs = new GiftSetting();
											gs.setReceived(0);
											gs.setDays(item.getGiftboxDaysToGet());
											gs.setName(item.getPackageName());
											gs.setSlug(item.getApplicationId());
											gs.setAppName(item.getTitle());
											gs.setPicture(item.getAvatar());
											gs.setTimeToReceive(Utils.calculateDaysToGetGift(item.getGiftboxDaysToGet()));
											onClick = new DialogInterface.OnClickListener() {
												@Override
												public void onClick(DialogInterface dialog, int which) {
													// TODO Auto-generated method stub
													db.addGift(gs);
													download(v, menuItem, 0, false, false, 1);
												}
											};
											am.showGiftDialog(R.string.gift_message_days, item.getGiftboxDaysToGet(), onClick);
										}
									}
								} else {
									download(v, menuItem, 0, isQuickDownload, false, 1);
								}
							} else {
								bgTask.checkVersionBought("", accessToken, v, menuItem);
							}
							isQuickDownload = false;
							isWatchMovie = false;
						}
					});
					popupMenu.show(v);
				} else {
					AlertDialogManager am = new AlertDialogManager(this);
					am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
								Intent intent = new Intent(DetailsActivity.this, LoginActivity.class);
								intent.putExtra("goback",true);
								startActivityForResult(intent,222);
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				}
			}else{
				if(enaG){
					//allow e
					if(true){//checkLogin()
						PopupMenu popupMenu = new PopupMenu(this);
						popupMenu.setHeaderTitle(getResources().getString(R.string.choose_version));
						String versionName;
						int versionId;
						String appId;
						int price1;
						int price2;
						for (int i = 0;i<item.getVersionList().size();i++) {
							versionId = item.getVersionList().get(i).getId();
							versionName = item.getVersionList().get(i).getName();
							appId = item.getApplicationId();
							price1 = item.getVersionList().get(i).getPrice1();
							price2 = item.getVersionList().get(i).getPrice2();
							popupMenu.add(versionId, versionName, appId, price1, price2, true).setIcon(getResources().getDrawable(R.drawable.ic_arrow_down));
						}  
						popupMenu.setOnItemSelectedListener(new OnItemSelectedListener() {
							@Override
							public void onItemSelected(final main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
								// TODO Auto-generated method stub
								if(menuItem.getPrice1() == 0 && menuItem.getPrice2() == 0){
									if(menuItem.getTitle().contains("Data") || menuItem.getTitle().contains("data")){
										isDownloadData = true;
									} else {
										isDownloadData = false;
									}
									if(menuItem.getTitle().contains("T-")){
										isDownloadEpisode = true;
									} else {
										isDownloadEpisode = false;
									}
									DetailsActivity.this.versionName = menuItem.getTitle();
									EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.DOWNLOAD_EVENT_CATEGORY, item.getTitle() + " of " + DetailsActivity.this.item.getTitle() + DetailsActivity.this.item.getApplicationType() + " store", Long.valueOf(1));
									if(item.getGiftbox() == 1){
										AlertDialogManager am = new AlertDialogManager(DetailsActivity.this);
										final DatabaseHelper db = new DatabaseHelper(DetailsActivity.this);
										GiftSetting gift = db.getGiftSync(item.getApplicationId());
										if(gift != null && gift.getReceived() == 1){
//											am.showPositiveDialog(R.string.gift_already_received, android.R.string.ok, new DialogInterface.OnClickListener() {
//												@Override
//												public void onClick(DialogInterface dialog, int which) {
//													dialog.dismiss();
//												}
//											});
											download(v, menuItem, 0, false, false, 1);
										} else {
											if(item.getGiftboxDaysToGet() == 0){
												final GiftSetting gs = new GiftSetting();
												gs.setReceived(0);
												gs.setDays(0);
												gs.setName(item.getPackageName());
												gs.setSlug(item.getApplicationId());
												gs.setAppName(item.getTitle());
												gs.setPicture(item.getAvatar());
												onClick = new DialogInterface.OnClickListener() {
													@Override
													public void onClick(DialogInterface dialog, int which) {
														// TODO Auto-generated method stub
														db.addGift(gs);
														download(v, menuItem, 0, false, false, 1);
													}
												};
												am.showGiftDialog(R.string.gift_message, 0, onClick);
											} else {
												final GiftSetting gs = new GiftSetting();
												gs.setReceived(0);
												gs.setDays(item.getGiftboxDaysToGet());
												gs.setName(item.getPackageName());
												gs.setSlug(item.getApplicationId());
												gs.setAppName(item.getTitle());
												gs.setPicture(item.getAvatar());
												gs.setTimeToReceive(Utils.calculateDaysToGetGift(item.getGiftboxDaysToGet()));
												onClick = new DialogInterface.OnClickListener() {
													@Override
													public void onClick(DialogInterface dialog, int which) {
														// TODO Auto-generated method stub
														db.addGift(gs);
														download(v, menuItem, 0, false, false, 1);
													}
												};
												am.showGiftDialog(R.string.gift_message_days, item.getGiftboxDaysToGet(), onClick);
											}
										}
									} else {
										download(v, menuItem, 0, isQuickDownload, false, 1);
									}
								} else {
									bgTask.checkVersionBought("", accessToken, v, menuItem);
								}
								isQuickDownload = false;
								isWatchMovie = false;
							}
						});
						popupMenu.show(v);
					} else {
						AlertDialogManager am = new AlertDialogManager(this);
						am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								switch (which) {
								case DialogInterface.BUTTON_POSITIVE:
									Intent intent = new Intent(DetailsActivity.this, LoginActivity.class);
									intent.putExtra("goback",true);
									startActivityForResult(intent,222);
									break;
								case DialogInterface.BUTTON_NEGATIVE:
									dialog.dismiss();
									break;
								}
							}
						});
					}
				}else{
					if(!countryCode.equalsIgnoreCase("id")&&!countryCode.equalsIgnoreCase("vn")&&!countryCode.equalsIgnoreCase("my")){
						if(item.getRootLink()!=null)
						{
							Intent gp = new Intent(Intent.ACTION_VIEW);
							gp.setData(Uri.parse(item.getRootLink()));
							startActivity(gp);
						}
					} else {
						if(true){//checkLogin()
							PopupMenu popupMenu = new PopupMenu(this);
							popupMenu.setHeaderTitle(getResources().getString(R.string.choose_version));
							String versionName;
							int versionId;
							String appId;
							int price1;
							int price2;
							for (int i = 0;i<item.getVersionList().size();i++) {
								versionId = item.getVersionList().get(i).getId();
								versionName = item.getVersionList().get(i).getName();
								appId = item.getApplicationId();
								price1 = item.getVersionList().get(i).getPrice1();
								price2 = item.getVersionList().get(i).getPrice2();
								popupMenu.add(versionId, versionName, appId, price1, price2, true).setIcon(getResources().getDrawable(R.drawable.ic_arrow_down));
							}  
							popupMenu.setOnItemSelectedListener(new OnItemSelectedListener() {
								@Override
								public void onItemSelected(final main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
									// TODO Auto-generated method stub
									if(menuItem.getPrice1() == 0 && menuItem.getPrice2() == 0){
										if(menuItem.getTitle().contains("Data") || menuItem.getTitle().contains("data")){
											isDownloadData = true;
										} else {
											isDownloadData = false;
										}
										if(menuItem.getTitle().contains("T-")){
											isDownloadEpisode = true;
										} else {
											isDownloadEpisode = false;
										}
										DetailsActivity.this.versionName = menuItem.getTitle();
										EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.DOWNLOAD_EVENT_CATEGORY, item.getTitle() + " of " + DetailsActivity.this.item.getTitle() + DetailsActivity.this.item.getApplicationType() + " store", Long.valueOf(1));
										if(item.getGiftbox() == 1){
											AlertDialogManager am = new AlertDialogManager(DetailsActivity.this);
											final DatabaseHelper db = new DatabaseHelper(DetailsActivity.this);
											GiftSetting gift = db.getGiftSync(item.getApplicationId());
											if(gift != null && gift.getReceived() == 1){
//												am.showPositiveDialog(R.string.gift_already_received, android.R.string.ok, new DialogInterface.OnClickListener() {
//													@Override
//													public void onClick(DialogInterface dialog, int which) {
//														dialog.dismiss();
//													}
//												});
												download(v, menuItem, 0, false, false, 1);
											} else {
												if(item.getGiftboxDaysToGet() == 0){
													final GiftSetting gs = new GiftSetting();
													gs.setReceived(0);
													gs.setDays(0);
													gs.setName(item.getPackageName());
													gs.setSlug(item.getApplicationId());
													gs.setAppName(item.getTitle());
													gs.setPicture(item.getAvatar());
													onClick = new DialogInterface.OnClickListener() {
														@Override
														public void onClick(DialogInterface dialog, int which) {
															// TODO Auto-generated method stub
															db.addGift(gs);
															download(v, menuItem, 0, false, false, 1);
														}
													};
													am.showGiftDialog(R.string.gift_message, 0, onClick);
												} else {
													final GiftSetting gs = new GiftSetting();
													gs.setReceived(0);
													gs.setDays(item.getGiftboxDaysToGet());
													gs.setName(item.getPackageName());
													gs.setSlug(item.getApplicationId());
													gs.setAppName(item.getTitle());
													gs.setPicture(item.getAvatar());
													gs.setTimeToReceive(Utils.calculateDaysToGetGift(item.getGiftboxDaysToGet()));
													onClick = new DialogInterface.OnClickListener() {
														@Override
														public void onClick(DialogInterface dialog, int which) {
															// TODO Auto-generated method stub
															db.addGift(gs);
															download(v, menuItem, 0, false, false, 1);
														}
													};
													am.showGiftDialog(R.string.gift_message_days, item.getGiftboxDaysToGet(), onClick);
												}
											}
										} else {
											download(v, menuItem, 0, isQuickDownload, false, 1);
										}
									} else {
										bgTask.checkVersionBought("", accessToken, v, menuItem);
									}
									isQuickDownload = false;
									isWatchMovie = false;
								}
							});
							popupMenu.show(v);
						} else {
							AlertDialogManager am = new AlertDialogManager(this);
							am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									switch (which) {
									case DialogInterface.BUTTON_POSITIVE:
										Intent intent = new Intent(DetailsActivity.this, LoginActivity.class);
										intent.putExtra("goback",true);
										startActivityForResult(intent,222);
										break;
									case DialogInterface.BUTTON_NEGATIVE:
										dialog.dismiss();
										break;
									}
								}
							});
						}
					}
				}
				
			}
			break;
		case R.id.btn_download_later:
			DatabaseHelper db = new DatabaseHelper(this);
			DownloadLaterItem dlItem = new DownloadLaterItem(item.getAvatar(), item.getTitle(), item.getAuthor(), item.getApplicationId());
			dlItem.setPrice1(item.getPrice());
			dlItem.setPrice2(item.getPrice2());
			dlItem.setPackageName(item.getPackageName());
			dlItem.setType(contentType);
			boolean added = db.addDownloadLater(dlItem);
			if(added){
				Toast.makeText(this, String.format(getResources().getString(R.string.saved), item.getTitle()), Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(this, String.format(getResources().getString(R.string.item_exist), item.getTitle()), Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.btn_checkDescription:
			//get des
			bgTask.getNewDescription(item.getApplicationId());
		}
	}
	
	public void onEventMainThread(final VersionBoughtEvent e){
		if(e.getItem().getTitle().contains("Data") || e.getItem().getTitle().contains("data")){
			isDownloadData = true;
		} else {
			isDownloadData = false;
		}
		if(e.getItem().getTitle().contains("T-")){
			isDownloadEpisode = true;
		} else {
			isDownloadEpisode = false;
		}
		DetailsActivity.this.versionName = e.getItem().getTitle();
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.DOWNLOAD_EVENT_CATEGORY, item.getTitle() + " of " + DetailsActivity.this.item.getTitle() + DetailsActivity.this.item.getApplicationType() + " store", Long.valueOf(1));
		if(item.getGiftbox() == 1){
			AlertDialogManager am = new AlertDialogManager(DetailsActivity.this);
			final DatabaseHelper db = new DatabaseHelper(DetailsActivity.this);
			GiftSetting gift = db.getGiftSync(item.getApplicationId());
			if(gift != null && gift.getReceived() == 1){
//				am.showPositiveDialog(R.string.gift_already_received, android.R.string.ok, new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						dialog.dismiss();
//					}
//				});
				download(e.getV(), e.getItem(), 0, false, false, 1);
			} else {
				if(item.getGiftboxDaysToGet() == 0){
					final GiftSetting gs = new GiftSetting();
					gs.setReceived(0);
					gs.setDays(0);
					gs.setName(item.getPackageName());
					gs.setSlug(item.getApplicationId());
					gs.setAppName(item.getTitle());
					gs.setPicture(item.getAvatar());
					onClick = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							db.addGift(gs);
							download(e.getV(), e.getItem(), 0, false, false, 1);
						}
					};
					am.showGiftDialog(R.string.gift_message, 0, onClick);
				} else {
					final GiftSetting gs = new GiftSetting();
					gs.setReceived(0);
					gs.setDays(item.getGiftboxDaysToGet());
					gs.setName(item.getPackageName());
					gs.setSlug(item.getApplicationId());
					gs.setAppName(item.getTitle());
					gs.setPicture(item.getAvatar());
					gs.setTimeToReceive(Utils.calculateDaysToGetGift(item.getGiftboxDaysToGet()));
					onClick = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							db.addGift(gs);
							download(e.getV(), e.getItem(), 0, false, false, 1);
						}
					};
					am.showGiftDialog(R.string.gift_message_days, item.getGiftboxDaysToGet(), onClick);
				}
			}
		} else {
			download(e.getV(), e.getItem(), 0, isQuickDownload, false, 1);
		}
	}
	
	public void onEventMainThread(final VersionNotBoughtEvent e){
		if(e.getItem().getTitle().contains("Data") || e.getItem().getTitle().contains("data")){
			isDownloadData = true;
		} else {
			isDownloadData = false;
		}
		if(e.getItem().getTitle().contains("T-")){
			isDownloadEpisode = true;
		} else {
			isDownloadEpisode = false;
		}
		DetailsActivity.this.versionName = e.getItem().getTitle();
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.DOWNLOAD_EVENT_CATEGORY, item.getTitle() + " of " + DetailsActivity.this.item.getTitle() + DetailsActivity.this.item.getApplicationType() + " store", Long.valueOf(1));
		if(item.getGiftbox() == 1){
			AlertDialogManager am = new AlertDialogManager(DetailsActivity.this);
			final DatabaseHelper db = new DatabaseHelper(DetailsActivity.this);
			GiftSetting gift = db.getGiftSync(item.getApplicationId());
			if(gift != null && gift.getReceived() == 1){
//				am.showPositiveDialog(R.string.gift_already_received, android.R.string.ok, new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						dialog.dismiss();
//					}
//				});
				download(e.getV(), e.getItem(), 0, false, false, 0);
			} else {
				if(item.getGiftboxDaysToGet() == 0){
					final GiftSetting gs = new GiftSetting();
					gs.setReceived(0);
					gs.setDays(0);
					gs.setName(item.getPackageName());
					gs.setSlug(item.getApplicationId());
					gs.setAppName(item.getTitle());
					gs.setPicture(item.getAvatar());
					onClick = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							db.addGift(gs);
							download(e.getV(), e.getItem(), 0, false, false, 0);
						}
					};
					am.showGiftDialog(R.string.gift_message, 0, onClick);
				} else {
					final GiftSetting gs = new GiftSetting();
					gs.setReceived(0);
					gs.setDays(item.getGiftboxDaysToGet());
					gs.setName(item.getPackageName());
					gs.setSlug(item.getApplicationId());
					gs.setAppName(item.getTitle());
					gs.setPicture(item.getAvatar());
					gs.setTimeToReceive(Utils.calculateDaysToGetGift(item.getGiftboxDaysToGet()));
					onClick = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							db.addGift(gs);
							download(e.getV(), e.getItem(), 0, false, false, 0);
						}
					};
					am.showGiftDialog(R.string.gift_message_days, item.getGiftboxDaysToGet(), onClick);
				}
			}
		} else {
			download(e.getV(), e.getItem(), 0, isQuickDownload, false, 0);
		}
	}
	
	public void onEventMainThread(BuySuccessEvent event){
		accessToken = Utils.getStaticAccessToken(this);
		if(isQuickDownload){
			bgTask.getDownloadLink("", accessToken, event.getSlug(), 0, Utils.getStaticIsRooted(this), "direct");
		} else {
			bgTask.getDownloadLink("", accessToken, event.getSlug(), event.getVersionId(), Utils.getStaticIsRooted(this), "direct");
		}
	}
	
	public void onEventMainThread(BuyFailEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		AppMsg.makeText(this, event.getMessage(), AppMsg.STYLE_ALERT, null).show();
	}
	
	private String[] can_play_list_host = new String[] {
			"http://download002.fshare.vn", "http://download003.fshare.vn",
			"http://download123.fshare.vn" };
	
	public void onEventMainThread(GetDownloadLinkSuccess event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		if(item.getInstallAttachApplication() == 1){
			accessToken = Utils.getStaticAccessToken(DetailsActivity.this);
			bgTask.buyAttachedContent(accessToken, item.getAttachApplicationSlug(), 0);
		}
		if(isWatchMovie){
			boolean available_host = false;
			for (int i = 0; i < can_play_list_host.length; i++) {
				if (event.getDl().getDownload().contains(can_play_list_host[i])) {
					if(!available_host){
						available_host = true;
						
					}
					
				}
			}
			Log.e("",available_host+ "CommonUtils.getDeviceName()" + CommonUtils.getDeviceName());
			if (CommonUtils.getDeviceName().equalsIgnoreCase("HTC")) {
				available_host = true;
			}
			if (available_host) {

				Intent watch = new Intent(DetailsActivity.this, VideoActivity.class);
				watch.putExtra(Constants.MOVIE_URL, event.getDl().getDownload());
				watch.putExtra(Constants.MOVIE_TITLE, item.getTitle());
				watch.putExtra(Constants.MOVIE_EPISODE, versionName);
				watch.putExtra(Constants.KEY_PRICE_1, item.getPrice());
				watch.putExtra(Constants.KEY_PRICE_2, item.getPrice2());
				watch.putExtra(Constants.KEY_VERSION, versionId);
				watch.putExtra(Constants.KEY_SLUG, item.getApplicationId());
				watch.putExtra(Constants.IS_MOVIE_PURCHASED, item.getBought());
				isWatchMovie = false;
				startActivity(watch);
			}else{
				showDialogSlowStreamVideo( item.getApplicationId());
			}
			
		} else {
			DownloadLink download = event.getDl();
			if(event.getSlug().equalsIgnoreCase(item.getApplicationId())){
				String url = download.getDownload();
				Uri srcUri = Uri.parse(url.replace(" ", "%20"));
				DownloadManager.Request request = new Request(srcUri);
				String title = "";
				if(isDownloadData){
					title = String.format(getString(R.string.additional_file), item.getTitle());
				} else if(isDownloadEpisode){
					title = item.getTitle() + " " + versionName;
				} else {
					title = item.getTitle();
				}
				request.setTitle(title);
				request.setDescription(item.getAvatar());
				setDownloadData(request, url, store);
				downloadManager.enqueue(request);
			} else {
				String url = download.getDownload();
				Uri srcUri = Uri.parse(url.replace(" ", "%20"));
				DownloadManager.Request request = new Request(srcUri);
				request.setTitle(event.getSlug());
				request.setDescription("");
				setDownloadData(request, url, "apps");
				downloadManager.enqueue(request);
			}
			List<String> extraUrls = download.getExtraDownloads();
			if(extraUrls.size() > 0 && extraUrls.get(0).length()>0){
				
				EventBus.getDefault().post(new Event.NoticeHasExtrasDataEvent());
				for(String extraUrl : extraUrls){
					Uri srcUri = Uri.parse(extraUrl.replace(" ", "%20"));
					DownloadManager.Request request = new Request(srcUri);
					if(extraUrl.endsWith("obb")){
						String obbDir = StorageUtils.OBB_ROOT + item.getPackageName() + "/";
						File obb = new File(obbDir);
						if(!obb.exists()){
							obb.mkdirs();
						}
						request.setDestinationUri(Uri.fromFile(new File(obbDir + Utils.getFileName(extraUrl))));
					} else {
						request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(extraUrl))));
					}
					request.setTitle(String.format(getResources().getString(R.string.additional_file), item.getTitle()));
					request.setDescription(item.getAvatar());
					request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
					AppStoreVnApplication.addDownload(Utils.getFileName(extraUrl), item.getPackageName());
					downloadManager.enqueue(request);
				}
			}
		}
	}
	
	public void onEventMainThread(GetDownloadLinkFailEvent e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		AppMsg.makeText(this, e.getMessage(), AppMsg.STYLE_ALERT, null).show();
	}
	
	public void onEventMainThread(NoticeHasExtrasDataEvent e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		AppMsg.makeText(this, getResources().getString(R.string.notice_extras_data), AppMsg.STYLE_INFO, null).show();
	}
	
	private boolean checkLogin(){
		return Utils.getStaticIsLogin(this);
	}
	
	private void setDownloadData(Request request, String url, String store){
		if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
			request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
		} else if(store.equalsIgnoreCase("books")){
			request.setMimeType(StorageUtils.EBOOK_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.EBOOK_ROOT + Utils.getFileName(url))));
		} else if(store.equalsIgnoreCase("comics")){
			request.setMimeType(StorageUtils.COMIC_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.COMIC_ROOT + Utils.getFileName(url))));
		} else if(store.equalsIgnoreCase("movies")){
			request.setMimeType(StorageUtils.MOVIES_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.MOVIES_ROOT + Utils.getFileName(url))));
		} else {
			request.setMimeType(StorageUtils.DATA_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.DATA_ROOT + Utils.getFileName(url))));
		}
	}

	private void validAndBuy(int price, String tymType, long versionId, int isBought){
		System.err.println("buy " + price + " " + tymType + " " + versionId);
//		Toast.makeText(this, "version: "+versionId+" | version: "+this.versionId, Toast.LENGTH_LONG).show();
		if(isBought == 1){
			if(pDialog == null){
				pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
			}
//			bgTask.buyContent("", Utils.getStaticAccessToken(this), item.getApplicationId(), versionId);
			if(isQuickDownload){
//				bgTask.getDownloadLink("", accessToken, event.getSlug(), 0, Utils.getStaticIsRooted(this), "direct");
				bgTask.getDownloadLink("",AccessTokenUtil.getInstance().init(this).getSavedAccessToken(), item.getApplicationId(), 0, Utils.getStaticIsRooted(this), "direct");
			} else {
				Log.e("download","download version:"+this.versionId);
				bgTask.getDownloadLink("", AccessTokenUtil.getInstance().init(this).getSavedAccessToken(), item.getApplicationId(), versionId, Utils.getStaticIsRooted(this), "direct");
			}
		} else {
			if(tymType.equalsIgnoreCase("green")){
				if(greenTym < price && greenTym != -1){
					AlertDialogManager am = new AlertDialogManager(this);
					am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
//								Intent intent = new Intent(DetailsActivity.this, PaymentActivity.class);
//								Bundle bundle = new Bundle();
//								bundle.putInt(AccountActivity.KEY_GREEN_TYM, greenTym);
//								bundle.putInt(AccountActivity.KEY_PURPLE_TYM, purpleTym);
//								intent.putExtras(bundle);
//								startActivity(intent);
								List<String> scopes = new ArrayList<String>();
								scopes.add("user.info");
								scopes.add("user.email");
								TopupAPI.getInstance().setContext(DetailsActivity.this).topupTYM(scopes, "");
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				} else if(greenTym == -1){
					AlertDialogManager am = new AlertDialogManager(this);
					am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				} else {
					Intent intent = new Intent(DetailsActivity.this, ConfirmBuyActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString(Constants.KEY_IMAGE, item.getAvatar());
					bundle.putString(Constants.KEY_NAME, item.getTitle());
					bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
					bundle.putInt(Constants.KEY_PRICE_1, item.getPrice());
					bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
					bundle.putLong(Constants.KEY_VERSION, versionId);
					bundle.putString(Constants.KEY_SLUG, item.getApplicationId());
					bundle.putString(Constants.KEY_EP, versionName);
					intent.putExtras(bundle);
					startActivityForResult(intent, 0);
				}
			} else if(tymType.equalsIgnoreCase("purple")){
				if(purpleTym < price && purpleTym != -1){
					AlertDialogManager am = new AlertDialogManager(this);
					am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
//								Intent intent = new Intent(DetailsActivity.this, PaymentActivity.class);
//								Bundle bundle = new Bundle();
//								bundle.putInt(AccountActivity.KEY_GREEN_TYM, greenTym);
//								bundle.putInt(AccountActivity.KEY_PURPLE_TYM, purpleTym);
//								intent.putExtras(bundle);
//								startActivity(intent);
								List<String> scopes = new ArrayList<String>();
								scopes.add("user.info");
								scopes.add("user.email");
								TopupAPI.getInstance().setContext(DetailsActivity.this).topupTYM(scopes, "");
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				} else if(purpleTym == -1){
					AlertDialogManager am = new AlertDialogManager(this);
					am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				} else {
					isWatchMovie = false;
					Intent intent = new Intent(DetailsActivity.this, ConfirmBuyActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString(Constants.KEY_IMAGE, item.getAvatar());
					bundle.putString(Constants.KEY_NAME, item.getTitle());
					bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
					bundle.putInt(Constants.KEY_PRICE_1, item.getPrice());
					bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
					bundle.putLong(Constants.KEY_VERSION, versionId);
					bundle.putString(Constants.KEY_SLUG, item.getApplicationId());
					bundle.putString(Constants.KEY_EP, versionName);
					intent.putExtras(bundle);
					startActivityForResult(intent, 0);
				}
			} else if(tymType.equalsIgnoreCase("free")){
				bgTask.buyContent("",Utils.getStaticAccessToken(this), item.getApplicationId(), versionId);
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		if(requestCode == 0 && resultCode == RESULT_OK){
			AppMsg.makeText(this, R.string.buy_success, AppMsg.STYLE_INFO, null).show();
			String accessToken = Utils.getStaticAccessToken(this);
			bgTask.getDownloadLink("",accessToken, item.getApplicationId(), intent.getExtras().getLong(Constants.KEY_VERSION), Utils.getStaticIsRooted(this), "direct");
		} else if(requestCode == 0 && resultCode == RESULT_CANCELED){
			
		} else if(requestCode == DetailsFragment.REQUEST_CODE_RESOLVE_ERR){
			
		} 
		else {
			if(fbLoginManager!=null){
				fbLoginManager.loginSuccess(intent);
			}
			if(intent!=null && intent.getExtras()!=null &&intent.getExtras().containsKey("tk")){
				accessToken=intent.getExtras().getString("tk");
				Log.e("gntk", "gntk"+accessToken);
				((AppStoreVnApplication) getApplication()).setLogin(true);
			}
			if(intent!=null && intent.hasExtra("oauth_verifier")){
				Log.e("LoginActivityResult","Get oauth_verifier: "+intent.getExtras().getString("oauth_verifier"));
				new GetTwitterAsync(intent.getExtras().getString("oauth_verifier")).execute();
			}
			if(resultCode == RESULT_CANCELED){
				if(pDialog!=null && pDialog.isShowing()){
					pDialog.dismiss();
				}
			}
		}
	}
	
	private class PackageEventReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_ADDED)) {
				String installedName = intent.getDataString().split(":")[1];
				if(item.getPackageName().equalsIgnoreCase(installedName)){
					layoutProgress.setVisibility(View.GONE);
					aq.id(R.id.btn_quick_download).gone();
					aq.id(R.id.btn_get_tr_download).gone();
					aq.id(R.id.btn_open).visible().enabled(true).clicked(DetailsActivity.this);
					aq.id(R.id.btn_uninstall).visible().clicked(DetailsActivity.this);
				}
			} else if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_REMOVED)) {
				String uninstalledName = intent.getDataString().split(":")[1];
				if(item.getPackageName().equalsIgnoreCase(uninstalledName)){
					layoutProgress.setVisibility(View.GONE);
					aq.id(R.id.btn_quick_download).visible().enabled(true).clicked(DetailsActivity.this);
					aq.id(R.id.btn_open).visibility(View.GONE).enabled(false);
					aq.id(R.id.btn_uninstall).gone();
				}
			}
		}
	}
	
	private class DownloadCanceledReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent.getAction().equalsIgnoreCase(Constants.ACTION_CANCEL_DOWNLOAD)){
				layoutProgress.setVisibility(View.GONE);
				aq.id(R.id.btn_quick_download).visible().clicked(DetailsActivity.this);
				aq.id(R.id.btn_open).visibility(View.GONE).enabled(false);
				aq.id(R.id.btn_uninstall).gone();
				cursor.close();
			}
		}
		
	}
	
	public void openEbook(String path){
		if(Utils.checkCoolReader(this, path)){
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse(path), "application/epub+zip");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else {
			AlertDialogManager am = new AlertDialogManager(this);
			am.showDialog(R.string.no_ebook_reader, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					AlertDialogManager am = new AlertDialogManager(DetailsActivity.this);
					String items[] = {"Cool Reader"};
					am.showDialogWithItems(R.string.choose_book_reader_app, items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface v, int pos) {
							// TODO Auto-generated method stub
							accessToken = Utils.getStaticAccessToken(DetailsActivity.this);
							bgTask.buyContent("", accessToken, "cooldreader", 0);
						}
					});
				}
			});
		}
	}
	
	private void openComic(String path){
		if(Utils.checkDroidComicViewer(this, path)){
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse(path), "application/x-acv");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else {
			AlertDialogManager am = new AlertDialogManager(this);
			am.showDialog(R.string.no_comic_reader, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					AlertDialogManager am = new AlertDialogManager(DetailsActivity.this);
					String items[] = {"Droid Comic Viewer"};
					am.showDialogWithItems(R.string.choose_book_reader_app, items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface v, int pos) {
							// TODO Auto-generated method stub
							accessToken = Utils.getStaticAccessToken(DetailsActivity.this);
							bgTask.buyContent("", accessToken, Utils.ACV_SLUG, 0);
						}
					});
				}
			});
		}
	}
	
	
	protected void showDialogSlowStreamVideo(final String slug) {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getResources().getString(R.string.notice))
				.setMessage(
						getResources().getString(R.string.slow_stream_video))
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						arg0.dismiss();
						accessToken = Utils
								.getStaticAccessToken(DetailsActivity.this);
						isWatchMovie = false;
						bgTask.buyContent("", accessToken, item.getApplicationId(),versionId);
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								arg0.dismiss();
							}
						});
		AlertDialog dialog = builder.create();
		dialog.setCancelable(false);
		dialog.show();
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.findItem(R.id.menu_account)
		.setTitle(getResources().getString(R.string.account));
		menu.findItem(R.id.menu_manage)
		.setTitle(getResources().getString(R.string.manage));
		menu.findItem(R.id.menu_setting)
		.setTitle(getResources().getString(R.string.setting));
		menu.findItem(R.id.menu_share_facebook)
		.setTitle(getResources().getString(R.string.facebook));
//		menu.findItem(R.id.menu_share_sms)
//		.setTitle(getResources().getString(R.string.sms));
		
		return true;
	}
	
	private CustomDialog dialog;
	public void showTorrentLinks( String[] action_play_list) {
		final ListView view = new ListView(this);
		view.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		view.setAdapter(new ArrayAdapter<String>(this,
				R.layout.list_item_single_choice, action_play_list));
		view.setItemChecked(0, true);
		dialog=new CustomDialog(this);
		dialog.setContentViewDialog(view);
		dialog.setCancelable(true);
		dialog.setCustomTitle("Torrent link(s)");
		dialog.setTitle(R.string.download_torrent_app_title);
		dialog.setRightButton("OK", new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder=new Builder(DetailsActivity.this);
				builder.setMessage(R.string.show_notice_open_torrent).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						int position = view.getCheckedItemPosition();
						DetailsActivity.this.dialog.dismiss();
						if(pDialog==null){
							pDialog=new ProgressDialog(DetailsActivity.this);
							pDialog.setMessage(getResources().getString(R.string.loading));
						}else if(!pDialog.isShowing()){
							pDialog.show();
						}
						bgTask.getTorrentDownloadLink(AccessTokenUtil.getInstance().init(DetailsActivity.this).getSavedAccessToken(), _verids.get(position));
					}

				}).create().show();
				
			}
		}).setLeftButton("Cancel", new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();

	}
	///
	public void showDownloadTorrentClient(){
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(R.string.message_title_dialog);
		builder.setMessage(R.string.download_torrent_app_msg);
		builder.setPositiveButton(
				getResources().getString(R.string.ok),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						// TODO Auto-generated method stub
						DownloadFile downloadFile = new DownloadFile();
						downloadFile.execute("http://dl03.sopcast.mobi/app/Torrent_1.14.apk");
						downloadUpdateProgress.show();
						downloadUpdateProgress
								.setOnCancelListener(new DialogInterface.OnCancelListener() {

									@Override
									public void onCancel(
											DialogInterface dialog) {

									}
								});
						// Intent intent = new
						// Intent(RootActivity.this,
						// DowloadUpdateService.class);
						// intent.putExtra("url", update_uri);
						// intent.putExtra("receiver", new
						// DownloadReceiver(new Handler()));
						// startService(intent);
					}
				});
		builder.create().show();
	}
	///
	private class DownloadFile extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... sUrl) {
			try {
				URL url = new URL(sUrl[0]);
				URLConnection connection = url.openConnection();
				connection.connect();
				// this will be useful so that you can show a typical 0-100%
				// progress bar
				int fileLength = connection.getContentLength();

				// download the file
				InputStream input = new BufferedInputStream(url.openStream());
				File folder = new File(
						Environment.getExternalStorageDirectory() + "/TorrentClientApp");
				boolean success = true;
				String filePath = null;
				if (!folder.exists()) {
					success = folder.mkdir();
				}
				if (success) {
					// Do something on success
					filePath = Environment.getExternalStorageDirectory()
							.getAbsolutePath() + "/TorrentClientApp/Torrent.apk";
					Log.e("FilePath", filePath);
				} else {
					// Do something else on failure
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							AppMsg.makeText(DetailsActivity.this,getResources().getString(R.string.couldntwitefile) , AppMsg.STYLE_CONFIRM, null).show();
						}
					});
					downloadUpdateProgress.dismiss();
				}

				OutputStream output = new FileOutputStream(filePath);

				byte data[] = new byte[1024];
				long total = 0;
				int count;
				while ((count = input.read(data)) != -1) {
					total += count;
					// publishing the progress....
					publishProgress((int) (total * 100 / fileLength));
					output.write(data, 0, count);
				}

				output.flush();
				output.close();
				input.close();
			} catch (Exception e) {
				e.printStackTrace();
				downloadUpdateProgress.dismiss();
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						AppMsg.makeText(DetailsActivity.this,getResources().getString(R.string.couldntdownloadnewversion) , AppMsg.STYLE_CONFIRM, null).show();
					}
				});
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			downloadUpdateProgress.show();
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			super.onProgressUpdate(progress);
			Log.e("onProgressUpdate","onProgressUpdate:"+progress[0]);
			downloadUpdateProgress.setProgress(progress[0]);
			if (progress[0] == 100) {
				File folder = new File(
						Environment.getExternalStorageDirectory() + "/TorrentClientApp");
				downloadUpdateProgress.dismiss();
				// start install latest update
				File fileLocation = new File(folder, "Torrent.apk");
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(fileLocation),
						"application/vnd.android.package-archive");
				startActivity(intent);
			}
		}
	}
	
	private void getTorrentForVersion(String link) {
		if(pDialog!=null&&pDialog.isShowing()){
			pDialog.dismiss();
		}
//		Toast.makeText(DetailsActivity.this, "Get torrent for version: "+vers[position], Toast.LENGTH_LONG).show();
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.parse(link), "application/x-bittorrent");
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		intent.putExtra("path", "/storage/sdcard0/");
		startActivity(intent);
	}
	
	public void onEventMainThread(GetTorrentDownloadLinkSuccess e){
		getTorrentForVersion(e.link);
//		if(e.versions.size()>0){
//			vers=e.versions.toArray(new String[e.versions.size()]);;
//			aq.id(R.id.btn_get_tr_download).text("Download Torrent");
////			aq.id(R.id.btn_get_tr_download).textColor(Color.BLUE);
//			aq.id(R.id.btn_get_tr_download).clicked(this);
//			links=e.links.toArray(new String[e.links.size()]);
//			if(!isCallable()){
//				showDownloadTorrentClient();
//			}else{
//				showTorrentLinks(vers);
//			}
//		}else{
//			aq.id(R.id.btn_get_tr_download).text("No Torrent");
//			aq.id(R.id.btn_get_tr_download).clicked(null);
//		}
		
	}
	
	public void onEventMainThread(final GetTorrentDownloadLinkFail e){
		if(pDialog!=null&&pDialog.isShowing()){
			pDialog.dismiss();
		}
//		if(e.error_code==2){
			//invalid link download
//			aq.id(R.id.btn_get_tr_download).visibility(View.INVISIBLE);
//			aq.id(R.id.btn_get_tr_download).clicked(null);
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					AppMsg.makeText(DetailsActivity.this,getResources().getString(R.string.error)+ "("+e.error_code+")", AppMsg.STYLE_INFO, null).show();
				}
			});
//			return;
//		}
//		aq.id(R.id.btn_get_tr_download).text("Get Torrent");
//		aq.id(R.id.btn_get_tr_download).clicked(this);
//		runOnUiThread(new Runnable() {
//			
//			@Override
//			public void run() {
//				AppMsg.makeText(DetailsActivity.this,getResources().getString(R.string.error)+ "("+e.error_code+")", AppMsg.STYLE_CONFIRM, null).show();
//			}
//		});
		
	}
	
	private boolean isCallable() {  
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.parse("http://test.vn/abc.torrent"), "application/x-bittorrent");
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,   
        PackageManager.MATCH_DEFAULT_ONLY);
        Log.e("isCallable","isCallable:"+list.size());
        return list.size() > 0;  
	}
	private class GetTwitterAsync extends AsyncTask<Void, Void, Void>{
		private String verifier;
		public GetTwitterAsync(String verifier){
			this.verifier=verifier;
		}
		@Override
		protected Void doInBackground(Void... params) {
			loginToTwitter(verifier);
			return null;
		}
		
	}
	private void loginToTwitter(String verifier) {
        // Check if already logged in
		if(verifier!=null){
			try{
			twitter4j.auth.AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
			Log.e("tVerifier",verifier);
            Editor e = mSharedPreferences.edit();
            e.putString(LoginActivity.PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
            e.putString(LoginActivity.PREF_KEY_OAUTH_SECRET,
                    accessToken.getTokenSecret());
            e.putLong(LoginActivity.PREF_USER_ID, accessToken.getUserId());
            e.putBoolean(LoginActivity.PREF_KEY_TWITTER_LOGIN, true);
            e.commit();
			//
            new ShareTwitterAsync(accessToken.getToken(), accessToken.getTokenSecret(), accessToken.getUserId()).execute();
			}catch(Exception ex){}
		}
    }
}
